using System;

using DevExpress.XtraEditors;
using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.CompositeUI.SmartParts;
using Microsoft.Practices.CompositeUI.EventBroker;
using Microsoft.Practices.ObjectBuilder;
using Module.Extension.FileManagerModule.Controller;
using BusinessEntity.Common;
using BusinessEntity.FileManagement;
using Client.BusinessAction.Constant;
using BusinessEntity.User;
using BusinessEntity.Patient;
using System.Text;
using System.IO;
using System.Windows.Forms;
using Common;
using System.Diagnostics;

namespace Module.Extension.FileManagerModule
{
    [SmartPart]
    public partial class FileManagerView : DevExpress.XtraEditors.XtraUserControl
    {
        private MyFile oFile;
        private bool mapLoaded = false;
        private FileManagerController controller;
        private BusinessEntity.Patient.Patient patient;
        private SortableCollection<MyFile> oFiles;

        #region FRAMEWORK FUNCTION / VARIABLES - DON'T CHANGE

        private WorkItem parentWorkItem;
        private Patient customer;

       

        [State(WorkItemStates.Patient)]
        public Patient Patient
        {
            set { patient = value; }
        }

        // We use our controller so we can show the comments page
        [CreateNew]
        public FileManagerController Controller
        {
            set { controller = value; }
        }

        [ServiceDependency]
        public WorkItem ParentWorkItem
        {
            set { parentWorkItem = value; }
        }

        public FileManagerView()
        {
            InitializeComponent();
        }
        #endregion

        public bool writeByteArrayToFile(byte[] buff, string fileName, out string storeFilename)
        {
            bool response = false;
            storeFilename = string.Empty;
            try
            {
                FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(buff);
                bw.Close(); //Thanks Karlo for pointing out!
                response = true;
                storeFilename = fs.Name;
                fs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return response;
        }
        [EventSubscription(EventNames.LoadFileManagement)]
        public void Load(object sender, EventArgs e)
        {
            GridMode(true);
         
        }

        [EventSubscription(EventNames.SaveFileManagement)]
        public void Save(object sender, EventArgs e)
        {
            //SortableCollection<MyFile> oFiles = null;
            //controller.Save(oFiles);
            
            if (oFile != null)
            {
                
                
                oFile.Note = txtNote.Text;
                oFile.FileName = txtFile.Text;
                oFile.PatientId = patient.Id;
                if (ddlNotificationTo.EditValue != null)
                    oFile.NotifyTo = (int)ddlNotificationTo.EditValue;
                else
                    oFile.NotifyTo = 0;

                if (ddlDocumentType.EditValue != null)
                    oFile.DocumentTypeId = (int)ddlDocumentType.EditValue;
                else
                    oFile.DocumentTypeId = 1;

                controller.Upload(oFile);
                simpleButton3_Click(null, null);
                BindGrid();
            }
            else
            {
                XtraMessageBox.Show("Kindly upload file first");
            }
            

        }
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            try
            {
                layoutControlFileBrowser.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                layoutControlFileViewer.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                GridMode(false);
                EnableControls();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            layoutControlFileBrowser.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            layoutControlFileViewer.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            GridMode(true);
            

        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog();

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    if (GetFileType(dlg.FileName) == ".pdf" || GetFileType(dlg.FileName) == ".doc" || GetFileType(dlg.FileName) == ".docx" || GetFileType(dlg.FileName) == ".xls" || GetFileType(dlg.FileName) == ".rtf" || GetFileType(dlg.FileName) == ".txt")
                    {

                        if (oFile == null)
                            oFile = new MyFile();

                   
                        txtFilePath.Text = dlg.FileName.ToString();
                        txtFile.Text = dlg.SafeFileName.ToString();
                        ddlFileExtension.EditValue  = GetFileTypeId(dlg.FileName);                      
                        System.IO.FileStream fs = null;
                        fs = new System.IO.FileStream(dlg.FileName, FileMode.Open, FileAccess.Read);
                        Byte[] blob = new Byte[fs.Length];
                        fs.Read(blob, 0, blob.Length);
                        fs.Close();
                        oFile.FileContent = blob;
                        oFile.Note = txtNote.Text;
                        oFile.FileTypeId = GetFileTypeId(dlg.FileName);
                        oFile.FileName = dlg.SafeFileName.ToString();//GetFileName(dlg.FileName);
                        oFile.SourceFileFullPath = dlg.FileName.ToString();
                        oFile.SourceFileName = dlg.SafeFileName.ToString();//oFile.FileName;
                        oFile.PatientId = patient.Id;
                      
                    }
                    else
                    {
                        XtraMessageBox.Show("Invalid file type");
                    }
                  
                   
                 }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(Utility.GetExceptionMessageString(ex), Utility.GetErrorMessageTitle(),
                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

      

        public static void ExecuteCommand(string Command, int Timeout)
        {
            try
            {

                //int ExitCode;
                ProcessStartInfo ProcessInfo;
                Process Process;
                ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + Command);
                ProcessInfo.CreateNoWindow = true;
                ProcessInfo.UseShellExecute = false;
                Process = Process.Start(ProcessInfo);
                //Process.WaitForExit();
                //ExitCode = Process.ExitCode;
                Process.Close();
            }
            catch { }

        }

   

        #region UI Requirements
        private void GridMode(bool IsGridOn)
        {
            if (IsGridOn == true)
            {
                simpleButton1.Enabled = true;
                simpleButton2.Enabled = true;
                simpleButton4.Enabled = true;
                simpleButton3.Enabled = false;
                BindGrid();
            }
            else
            {
                simpleButton1.Enabled = false;
                simpleButton2.Enabled = false;
                simpleButton4.Enabled = false;
                simpleButton3.Enabled = true;
                BindFileType();
                BindNotificationTo();
                BindDocumentType();
            }
            clearContents();
        }
        private void DisableControls()
        {
            btnUpload.Enabled = false;
            txtFile.Properties.ReadOnly = true;
            ddlNotificationTo.Properties.ReadOnly = true;
            txtFilePath.Properties.ReadOnly = true;
            ddlFileExtension.Properties.ReadOnly = true;
        }
        private void EnableControls()
        {
            btnUpload.Enabled = true;
            txtFile.Properties.ReadOnly = false;
            ddlNotificationTo.Properties.ReadOnly = false;
            txtFilePath.Properties.ReadOnly = false;
            ddlFileExtension.Properties.ReadOnly = false;
        }
        private void clearContents()
        {
            txtFile.Text = string.Empty;
            txtFilePath.Text = string.Empty;
            txtNote.Text = string.Empty;
            ddlFileExtension.Text = string.Empty;
        }
#endregion
        
        #region Get Methods
        private string GetFileType(string fileName)
        {
            int indexDot = fileName.LastIndexOf(".");
            if (indexDot > 0)
            {
                fileName = fileName.Substring(indexDot, fileName.Length - indexDot);
                return fileName;
            }
            else
            {
                return string.Empty;

            }
        }

        private int GetFileTypeId(string fileName)
        {
            int FileType = 0;
            fileName = GetFileType(fileName);

            switch (fileName)
            {
                case ".doc":
                    FileType = 1;
                    break;
                case ".docx":
                    FileType = 2;
                    break;
                case ".pdf":
                    FileType = 3;
                    break;
                case ".xls":
                    FileType = 4;
                    break;
                case ".rtf":
                    FileType = 5;
                    break;
                case ".txt":
                    FileType = 6;
                    break;
                default:
                    FileType = 0;
                    break;
            }


            return FileType;


        }

     private string GetFileName(string fullfilePath)
        {
            int indexDot = fullfilePath.LastIndexOf(@"\");
            if (indexDot > 0)
            {
                fullfilePath = fullfilePath.Substring(indexDot + 1, fullfilePath.Length - indexDot - 1);
                return fullfilePath;
            }
            else
            {
                return string.Empty;
            }
        }
        #endregion

        #region Bind Controls
        private void BindGrid()
        {
            MyFile oSearchMyFile = new MyFile();
            oSearchMyFile.PatientId = patient.Id;
            //specify search criteria, if required.
            oFiles = controller.Load(oSearchMyFile);
            gridControl1.DataSource = oFiles;
            //GridMode(true);
        }
        private void PopulateDatainControl()
        {
            if (oFiles != null)
            {
                oFile = (MyFile)gridView1.GetFocusedRow();
                if (oFile != null)
                {
                    txtNote.Text = oFile.Note.ToString();
                    ddlDocumentType.EditValue = oFile.DocumentTypeId;
                    ddlNotificationTo.EditValue = oFile.NotifyTo;
                    txtFile.Text = oFile.FileName;
                    txtFilePath.Text = oFile.SourceFileFullPath;
                    ddlFileExtension.EditValue = GetFileTypeId(oFile.FileName);
                }
            }
        }
        private void BindFileType()
        {
            SortableCollection<MyFileType> oFileTypes = controller.LoadFileType();
            ddlFileExtension.Properties.DataSource = oFileTypes;
            ddlFileExtension.Properties.DisplayMember = "Name";
            ddlFileExtension.Properties.ValueMember = "Id";
        }
        private void BindNotificationTo()
        {
            SortableCollection<CoreUser> oCoreUsers = controller.LoadCoreUsers();
            ddlNotificationTo.Properties.DataSource = oCoreUsers;
            ddlNotificationTo.Properties.DisplayMember = "LoginId";
            ddlNotificationTo.Properties.ValueMember = "Id";
        }

        private void BindDocumentType()
        {
            SortableCollection<DocumentType> oDocTypess = controller.LoadDocumentType();
            ddlDocumentType.Properties.DataSource = oDocTypess;
            ddlDocumentType.Properties.DisplayMember = "Name";
            ddlDocumentType.Properties.ValueMember = "Id";
        }

        #endregion

        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
           
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            if (oFiles != null)
            {
                
                MyFile oMyFile = (MyFile)gridView1.GetFocusedRow();
                if (oMyFile != null)
                {
                    oFiles.Remove(oMyFile);
                    controller.DeleteFile((int)oMyFile.Id);
                }
            }

        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            MyFile oSearchMyFile = new MyFile();
            SortableCollection<MyFile> oFiles = controller.Load(oSearchMyFile);
            MyFile oMyFile = (MyFile)gridView1.GetFocusedRow();

            string storeFilename = string.Empty;
            if (this.writeByteArrayToFile(oMyFile.FileContent, oMyFile.FileName, out storeFilename))
            {
                if (storeFilename.Length > 0)
                {
                    Process.Start(storeFilename);
                }
            }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            try
            {
                layoutControlFileBrowser.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                layoutControlFileViewer.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                GridMode(false);
                DisableControls();
                PopulateDatainControl();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }

        private void ddlNotificationTo_EditValueChanged(object sender, EventArgs e)
        {

        }


        
       

       

     

      
       
    }
}
